<template>
  <div class="main-content">
    <!-- Button to open the dialog -->
    <!-- <el-button type="primary" @click="openDialog">修改密码</el-button> -->

    <!-- Dialog for changing password -->
    <el-dialog
      v-model="dialogVisible"
      title="修改密码"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="password-form"
        status-icon
      >
        <!-- 1. Original Password -->
        <el-form-item label="原密码" prop="originalPassword">
          <el-input 
            v-model="ruleForm.originalPassword" 
            type="password" 
            placeholder="请输入原密码" 
            show-password 
          />
        </el-form-item>

        <!-- 2. New Password -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="ruleForm.newPassword" 
            type="password" 
            placeholder="需包含字母+数字, 6-20位" 
            show-password 
          />
           <!-- The red error message from the screenshot will appear here automatically on validation failure -->
        </el-form-item>

        <!-- 4. Confirm Password -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="ruleForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            show-password 
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <!-- The "返回" (Back) button from the screenshot is typically a "Cancel" button -->
          <el-button @click="handleClose">返回</el-button>
          <!-- 3. Save Button -->
          <el-button 
            type="success" 
            class="save-button" 
            @click="submitForm(ruleFormRef)"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { resetCurUserPwd } from '@/api/system/user'

// --- Refs for Dialog and Form ---
const dialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()

// --- Form Data ---
const ruleForm = reactive({
  originalPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// --- Custom Validators ---

// Validator for New Password
const validateNewPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度必须在 6 到 20 个字符之间'))
  } else if (!/^(?=.*[A-Za-z])(?=.*\d)/.test(value)) {
    callback(new Error('密码必须同时包含字母和数字'))
  } else if (value === ruleForm.originalPassword) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    // Also trigger validation for the confirm password field
    if (ruleForm.confirmPassword !== '') {
      ruleFormRef.value?.validateField('confirmPassword', () => {})
    }
    callback()
  }
}

// Validator for Confirm Password
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.newPassword) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

// --- Form Validation Rules ---
const rules = reactive<FormRules<typeof ruleForm>>({
  originalPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
})

// --- Methods ---

const openDialog = () => {
  dialogVisible.value = true
}

const handleClose = () => {
  // Reset form fields and validation before closing
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  dialogVisible.value = false
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
       const result=await resetCurUserPwd(ruleForm.originalPassword, ruleForm.newPassword)
       if(result){
        ElMessage({
          message: '密码修改成功!',
          type: 'success',
        })
       }
      handleClose() // Close and reset the dialog
    } else {
      console.log('Validation Error!', fields)
    }
  })
}

defineExpose({
  openDialog
})
</script>

<style scoped>
/* Scoped styles to match the look in the image */
.main-content {
  padding: 20px;
  background: #fff;
}

.password-form {
  padding-right: 40px; /* Add some space on the right */
}

/* Style for the green 'Save' button */
.save-button {
  background-color: #a5d96f;
  border-color: #a5d96f;
  color: #ffffff;
}
.save-button:hover {
  background-color: #b3e28c;
  border-color: #b3e28c;
}
</style>
